import { Component , PropTypes } from "react";

export default class LazyImgCom extends Component{
    constructor(){
        super()
        this.state = {
            imgUrl : './../images/defaultImg.png',
            errorImg:''
        }
    }
    static defaultProp = {
        imageUrl : ''
    };
    static contextTypes = {
        Pagination: PropTypes.object
    };
    //组件挂载之后
    componentDidMount(){
        let _this = this ;
        this.handleImageLoaded() ;
        this.context.Pagination.on('scroll',() => {
            this.handleImageLoaded()
        })
    }
    handleImageLoaded(){
        let { imageUrl } = this.props ;
        let { offsetTop } = this.refs.img ;
        let { Pagination } = this.context ;
        let wrapperHeight = Pagination.wrapperHeight ;
        let PaginationY = Pagination.y ;
        if(Math.abs(PaginationY) + wrapperHeight > offsetTop){
            clearTimeout(timer) ;
            this.context.Pagination.off('scroll')  ;
            let timer = setTimeout(() => {
                this.setState({
                    imgUrl : imageUrl
                })
            }, 500);
        }
    }
    handleImageErrored(){
        const { errorImg } = this.state ;
        this.setState({
            imgUrl : errorImg
        })
    }
    render(){
        let { imgUrl } = this.state ;
        return (
            <img 
                src={imgUrl}
                onLoad={this.handleImageLoaded.bind(this)}
                onError={this.handleImageErrored.bind(this)}
                ref="img"
            />
        )
    }
}